/**
 * @author Alfort Robert - Köckinger Martin
 * This Class handles the decoding functionality
 * @version 2.1
 */

package at.fhj.itm;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

/**
 * Is Called when QRCodeDecode calls the decode function 
 * @params String
 * @params Integer
 * @params String
 * @see android.os.AsyncTask
 */
public class QRDecoder extends AsyncTask<String, Integer, String> {

	private String s; /** Creating a String for handling Text */

	/**
	 * Implements the handle code for decoding Images.
	 * @params String input
	 * @return String s
	 */
	public String getQRDecode(final String input) {
		Log.i("Request", "Threading started");
		Log.i("Data:", "Recived input: " + input);

		/*
		 * retriving input String
		 * String split up and calculated length to find out Filename
		 */
		String filePath = input;
		String[] filePathNeu = filePath.split("/");
		int filePathLength = filePathNeu.length;
		
		Log.i("Filelenght:",String.valueOf(filePathLength));
		Log.i("FileName:",filePathNeu[filePathLength-1].toString());
		
		try {
			/*
			 * File is send to following URL which decodes a picture
			 */
			FileInputStream fis = new FileInputStream(filePath);
			HttpFileUploader htfu = new HttpFileUploader(
					"http://zxing.org/w/decode", "f", filePathNeu[filePathLength-1].toString());
			htfu.doStart(fis);
			s = htfu.s;
			// return bm;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return s;
	}

	/**
	 * Calculating data in Background
	 * Interface is accessable
	 * @params String... inputData
	 * @return String
	 */
	@Override
	protected String doInBackground(String... inputData) {
		String input = inputData[0];
		return this.getQRDecode(input);
	}

	/**
	 * After Calculating Data
	 * After setting Text to EditText txtOurPut temp Image File will be deleted
	 * @params String result
	 */
	@Override
	protected void onPostExecute(String result) {
		Log.i("BACKGROUND", "Data calculated.");
		QRCodeDecode.txtOutPut.setText(s);
		
		/*
		 * If Image was created by Camera (IMG_tmp)
		 * Then delete it afterwords
		 */
		File tmpFile = new File(Environment.getExternalStorageDirectory().toString()+"/IMG_tmp.png");
		if (tmpFile.exists()) {
			Log.i("Deleting","Deleted IMG_tmp File");
			tmpFile.delete();
		}
		
	}
}
